package fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.android.volley.Response;
import com.android.volley.VolleyError;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import adapter.DiscoverGridviewAdapter;
import bean.Oil;
import utils.RequestQueueUtils;
import zhang.automobileservice.CarfriendActivity;
import zhang.automobileservice.MovercarActivity;
import zhang.automobileservice.NewsConsultActivity;
import zhang.automobileservice.R;

/**
 * Created by Administrator on 2016/7/18.
 */
public class DiscoverFragment extends Fragment implements View.OnClickListener {
    private GridView gv_view;
    private ArrayList<Oil> arrayList;
    private ImageView im_carfriend;
    private ImageView im_carhelper;
    private ImageView im_carconsule;
    private RelativeLayout rl_carcircle;
    private RelativeLayout rl_helper;
    private RelativeLayout rl_consule;

    private String pro = "";
    private TextView tv_provence;

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    Log.e("======", "amapLocation.getDistrict()");
                    //定位成功回调信息，设置相关消息
                    amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                    amapLocation.getLatitude();//获取纬度
                    amapLocation.getLongitude();//获取经度
                    amapLocation.getAccuracy();//获取精度信息
                    /*SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date = new Date(amapLocation.getTime());
                    df.format(date);//定位时间*/
                    amapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
                    amapLocation.getCountry();//国家信息
                    pro = amapLocation.getProvince();//省信息
                    amapLocation.getCity();//城市信息
                    amapLocation.getDistrict();//城区信息
                    amapLocation.getStreet();//街道信息
                    amapLocation.getStreetNum();//街道门牌号信息
                    amapLocation.getCityCode();//城市编码
                    amapLocation.getAdCode();//地区编码
                    amapLocation.getAoiName();//获取当前定位点的AOI信息
                } else {
                    //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
                tv_provence.setText(amapLocation.getCity() + "●今日油价");
                Message message = new Message();
                message.what = 0x001;
                message.obj = pro;
                handler.sendMessage(message);
            }

        }
    };

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x001) {
                pro = (String) msg.obj;
            }
            initData();
        }
    };
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_discover, null);
        initView(view);
        getAddress();
        return view;
    }


    private void getAddress() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getContext());
//设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
//设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
//设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(true);

        if (mLocationOption.isOnceLocationLatest()) {
            mLocationOption.setOnceLocationLatest(true);
//设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。
//如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会。
        }

//设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
//设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
//设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(50000000);
//给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
//启动定位
        mLocationClient.startLocation();
    }

    private void initData() {
        arrayList = new ArrayList<>();
        String url = "http://route.showapi.com/138-46?showapi_appid=20077&showapi_sign=c23cae77a0db4753867830987143bbf1&prov=" + pro.split("省")[0];
        RequestQueueUtils.exectueJsonRequest(getActivity(), url, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject o) {
                try {
                    if ("0".equals(o.getString("showapi_res_code"))) {
                        JSONObject object = o.getJSONObject("showapi_res_body").getJSONArray("list").getJSONObject(0);
                        arrayList.add(new Oil("90", object.getString("p90")));
                        arrayList.add(new Oil("93", object.getString("p93")));
                        arrayList.add(new Oil("97", object.getString("p97")));
                        arrayList.add(new Oil("0", object.getString("p0")));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                gv_view.setAdapter(new DiscoverGridviewAdapter(getContext(), arrayList));
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
    }

    private void initView(View view) {
        gv_view = (GridView) view.findViewById(R.id.gv_view);
        im_carfriend = (ImageView) view.findViewById(R.id.im_carfriend);
        im_carfriend.setOnClickListener(this);
        im_carhelper = (ImageView) view.findViewById(R.id.im_carhelper);
        im_carhelper.setOnClickListener(this);
        im_carconsule = (ImageView) view.findViewById(R.id.im_carconsule);
        im_carconsule.setOnClickListener(this);
        tv_provence = (TextView) view.findViewById(R.id.tv_provence);
        tv_provence.setOnClickListener(this);
        rl_carcircle = (RelativeLayout) view.findViewById(R.id.rl_carcircle);
        rl_carcircle.setOnClickListener(this);
        rl_helper = (RelativeLayout) view.findViewById(R.id.rl_helper);
        rl_helper.setOnClickListener(this);
        rl_consule = (RelativeLayout) view.findViewById(R.id.rl_consule);
        rl_consule.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_helper:
                Intent intent = new Intent(getActivity(), MovercarActivity.class);
                startActivity(intent);
                break;
            case R.id.rl_carcircle:
                Intent intent1 = new Intent(getActivity(), CarfriendActivity.class);
                startActivity(intent1);
                break;
            case R.id.rl_consule:
                Intent intent2 = new Intent(getActivity(), NewsConsultActivity.class);
                startActivity(intent2);
                break;
        }
    }
}
